package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.PageBean;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired(required = false)
    private SetmealMapper setmealMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required =false)
    private SetmealDishMapper setmealDishMapper;

    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private SalesMapper salesMapper;
    /**
     * 分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R<PageBean> findPage(int page, int pageSize, String name) {
        //开启分页
        PageHelper.startPage(page,pageSize);
        //查询所有数据
        List<Setmeal> setmealList = setmealMapper.findAllSetmeal(page,pageSize,name);
        //获取分页对象
        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealList);
        //创建SetmealDto集合接收要被拓展数据的分页数据
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (Setmeal setmeal :  pageInfo.getList()) {
            SetmealDto setmealDto = new SetmealDto();
            //复制属性值，源对象有就复制，没有就不复制
            BeanUtils.copyProperties(setmeal,setmealDto);
            //设置套餐分类
            setmealDto.setCategoryName(categoryMapper.findCategoryNameById(setmeal.getCategoryId()));
            setmealDtoList.add(setmealDto);
        }
        return R.success(new PageBean(setmealDtoList,pageInfo.getTotal(),pageSize,page));
    }

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @Transactional
    @Override
    public R<String> addSetMeal(SetmealDto setmealDto) {
        //完善数据
        setmealDto.setCreateTime(LocalDateTime.now());
        setmealDto.setUpdateTime(LocalDateTime.now());
        try {
            //插入套餐数据
            int addSetmeal = setmealMapper.addSetmeal(setmealDto);
            List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
            //批量处理套餐内菜品数据
            List<SetmealDish>  setmealDishList= setmealDishes.stream().map(setmealDish -> {
                setmealDish.setSetmealId(setmealDto.getId());
                setmealDish.setSort(0);
                setmealDish.setCreateTime(setmealDto.getCreateTime());
                setmealDish.setUpdateTime(setmealDto.getUpdateTime());
                setmealDish.setCreateUser(setmealDto.getCreateUser());
                setmealDish.setUpdateUser(setmealDto.getUpdateUser());
                return setmealDish;
            }).collect(Collectors.toList());
            //批量插入套餐内菜品数据
            int addBatchSetmealDishResult = setmealDishMapper.addBatchSetmealDish(setmealDishList);
        }catch (Exception e){
            e.printStackTrace();
            return R.error("添加失败，服务器内部错误");
        }


        return R.success("添加成功");
    }

    /**
     * 根据id查询套餐以及套餐内菜品数据回显前端
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public R<SetmealDto> findSetmealDtoById(Long id) {
        SetmealDto setmealDto = new SetmealDto();
        try {
            Setmeal setmeal = setmealMapper.findSetmealById(id);
            List<SetmealDish> setmealDishList = setmealDishMapper.findSetmealDishListBySetmealId(id);
            BeanUtils.copyProperties(setmeal,setmealDto);
            setmealDto.setSetmealDishes(setmealDishList);
        }catch (Exception e){
            throw new CustomException("查询失败");
        }

        return R.success(setmealDto);
    }

    /**
     * 更新套餐和套餐内菜品
     *
     * @param setmealDto
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @Transactional
    @Override
    public R<String> updateSetmeal(SetmealDto setmealDto) {
        try {
            setmealDto.setUpdateTime(LocalDateTime.now());
            //更新套餐数据
            setmealMapper.updateSetmeal(setmealDto);
            //删除套餐内原始菜品
            setmealDishMapper.deleteBySetmealId(setmealDto.getId());
            //处理新套餐内菜品数据
            List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
            List<SetmealDish> setmealDishList = setmealDishes.stream().map(setmealDish -> {
                setmealDish.setSetmealId(setmealDto.getId());
                setmealDish.setSort(0);
                setmealDish.setCreateTime(setmealDto.getCreateTime());
                setmealDish.setUpdateTime(setmealDto.getUpdateTime());
                setmealDish.setCreateUser(setmealDto.getCreateUser());
                setmealDish.setUpdateUser(setmealDto.getUpdateUser());
                return setmealDish;
            }).collect(Collectors.toList());
            setmealDishMapper.addBatchSetmealDish(setmealDishList);
        }catch (Exception e){
            throw new CustomException("修改失败");
        }

        return R.success("修改成功");
    }

    /**
     * 批量更新套餐状态
     *
     * @param status
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @Override
    public R<String> updateSetmealStatusByIds(int status, long[] ids) {
        return setmealMapper.updateSetmealStatusByIds(status,ids)>0?R.success("更新成功"):R.error("更新失败");
    }

    /**
     * 批量删除套餐
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "setmealCache",allEntries = true)
    @Override
    public R<String> deleteSetmealByIds(Long[] ids) {
        //判断要删除的套餐是否包含在售套餐，有则抛出异常
        if(setmealMapper.findSetmealIsSaleByIds(ids)>0){
            throw new CustomException("当前删除操作包含在售套餐，请重新选择");
        }
        for (Long id : ids) {
            //删除套餐内菜品数据
            setmealDishMapper.deleteBySetmealId(id);
        }

        return setmealMapper.deleteSetmealByIds(ids)>0 ? R.success("删除成功"):R.error("删除失败");
    }

    /**
     * 查询在售套餐
     *
     * @param categoryId
     * @param status
     * @return
     */
    @Cacheable(value = "setmealCache",key = "#categoryId+'_'+#status")
    @Override
    public List<SetmealDto> findsetmealListById(Long categoryId, Integer status) {
        List<Setmeal> setmealList = setmealMapper.findSetmealByCategoryIdAndStatus(categoryId,status);
        List<SetmealDto> setmealDtoList = new ArrayList<>();
        for (Setmeal setmeal : setmealList) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,setmealDto);
            String month = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
            setmealDto.setMonthlySales(salesMapper.findSetmealMonthlySales(setmeal.getId(),month));
            setmealDtoList.add(setmealDto);
        }
        return setmealDtoList;
    }

    /**
     * 查询套餐内菜品信息
     * @param setmealId
     * @return
     */
    @Override
    public R<List<SetmealDishDto>> findsetmealDishById(Long setmealId) {
        List<SetmealDish> setmealDishListBySetmealId = setmealDishMapper.findSetmealDishListBySetmealId(setmealId);
        List<SetmealDishDto> setmealDishDtoList = new ArrayList<>();
        for (SetmealDish setmealDish : setmealDishListBySetmealId) {
            SetmealDishDto setmealDishDto = new SetmealDishDto();
            BeanUtils.copyProperties(setmealDish,setmealDishDto);
            setmealDishDto.setImage(dishMapper.findImageNameById(setmealDish.getDishId()));
            setmealDishDtoList.add(setmealDishDto);
        }

        return R.success(setmealDishDtoList);
    }
}
